<script setup>
import { ref, onMounted, defineProps, computed } from 'vue'
import {
  saveCourse,
  getSingleCourseInfo,
  submitCourse,
  uploadCourseAPI,
  downCourse,
  upCourse,
  deleteCourse,
  reEditCourse,
} from '@/services/course'
import { useUserStore } from '@/stores'
import { getCategoryAPI } from '@/services/table'
import { watch } from 'vue'

const uploadCourse = async () => {
  formRef.value.validate().then(async (res) => {
    uni.showLoading({
      title: '发布中',
      mask: true,
    })
    await uploadCourseAPI({ ...params.value, userName: userStore.user.userName })
    refreshPrev()
  })
}

//oss直传
const videoUrl = ref()
const host = 'https://crop-doctor.oss-cn-beijing.aliyuncs.com'
const signature = '<signatureString>'
const ossAccessKeyId = 'LTAI5tLHGKbrK2XaVQFyZ6X7'
const policy = '<policyBase64Str>'
const key = 'vRWLicleAgRb8Gq0o8eAn9GeBTUxOj'
const securityToken = '<x-oss-security-token>'
const filePath = '<filePath>' // 待上传文件的文件路径。
const upload = () => {
  uni.chooseVideo({
    sourceType: ['camera', 'album'],
    success: async function (res) {
      //选择图片成功回调
      uni.showLoading({
        title: '上传中',
        mask: true,
      })
      var tempPath = res.tempFilePath
      var dir = 'video/'
      //发起后端请求签名
      uni.request({
        url: 'https://bio-smart.cn/doctor/video/getSign',
        data: { dir: dir },
        success: function (res) {
          var l = tempPath.length
          var newName = Date.parse(new Date()) + tempPath.substring(l - 10)
          //发起putObject请求，直传OSS
          uni.uploadFile({
            url: 'https://crop-doctor.oss-cn-beijing.aliyuncs.com',
            filePath: tempPath,
            name: 'file',
            header: {
              'Content-Type': 'multipart/form-data',
            },
            formData: {
              name: newName,
              key: dir + newName,
              policy: res.data.data.policy,
              OSSAccessKeyId: res.data.data.accessId,
              success_action_status: '200',
              signature: res.data.data.signature,
            },
            success: function (res) {
              uni.hideLoading()
              params.value.url = `https://crop-doctor.oss-cn-beijing.aliyuncs.com/${dir + newName}`
            },
          })
        },
      })
    },
  })
}

const userStore = useUserStore()
const props = defineProps({
  id: {
    type: Number,
  },
  index: {
    type: Number,
  },
})

const params = ref({
  id: props.id,
  title: '',
  description: '',
  mt: '',
  st: '',
  url: '',
})
const able = ref(false)
const loading = ref(true)
onMounted(async () => {
  let res
  loading.value = true
  if (props.id) {
    res = await getSingleCourseInfo(props.id, props.index)
  }
  loading.value = false
  params.value = res.data
})

watch(
  () => params.value.mt,
  (newMt) => {
    params.value.category = newMt + ' ' + params.value.st
  },
)
watch(
  () => params.value.st,
  (newSt) => {
    params.value.category = params.value.mt + ' ' + newSt
  },
)
let st1 = []
let st2 = []
const columns = ref()
const columnData = ref()
const getCategory = async () => {
  let res = await getCategoryAPI('水果')
  st1 = res.data.map((item) => {
    return item.st
  })
  res = await getCategoryAPI('蔬菜')
  st2 = res.data.map((item) => {
    return item.st
  })
  columns.value = [['水果', '蔬菜'], st1]
  columnData.value = [st1, st2]
}
getCategory()
const picker = ref()
const openPicker = () => {
  props.index === 0 && picker.value.open()
  uni.hideKeyboard() //隐藏键盘
}
const confirm = (e) => {
  params.value.mt = e.value[0]
  params.value.st = e.value[1]
}

const change = (e) => {
  const { columnIndex, index } = e
  if (columnIndex === 0) {
    picker.value.setColumnValues(1, columnData.value[index])
  }
}

const rules = {
  title: [
    {
      type: 'string',
      required: true,
      message: '请填写标题',
      trigger: ['blur', 'change'],
    },
    {
      min: 2,
      max: 30,
      message: '长度在2-30个字符之间',
    },
  ],
  category: {
    type: 'string',
    required: true,
    message: '请选择相关分类',
  },
  url: {
    required: true,
    message: '请上传视频',
  },
  description: {
    required: true,
    message: '请输入科普视频描述',
  },
}

const formRef = ref()
const save = () => {
  formRef.value
    .validate()
    .then(async (res) => {
      await saveCourse(params.value)
      uni.showLoading({
        title: '保存中',
        mask: true,
      })
      refreshPrev()
    })
    .catch((errors) => {
      uni.showToast({
        icon: 'error',
        title: '校验失败',
      })
    })
}
const reEdit = async () => {
  uni.showLoading({
    title: '重新编辑..',
    mask: true,
  })
  await reEditCourse(props.id)
  refreshPrev()
}
const submit = () => {
  uni.showLoading({
    title: '提交中',
    mask: true,
  })
  formRef.value.validate().then(async (res) => {
    await submitCourse(params.value)
    refreshPrev()
  })
}

const reset = () => {
  formRef.value.resetFields()
  formRef.value.clearValidate()
}

//上架下架
function refreshPrev() {
  setTimeout(() => {
    uni.hideLoading()
    const pages = getCurrentPages()
    const prevPage = pages[pages.length - 2] // 获取上一个页面实例对象
    uni.navigateBack({
      delta: 1,
      success: function () {
        uni.showToast({
          icon: 'success',
          title: '成功',
        })
        prevPage.onLoad(props.index) // 执行上一页的onLoad函数
      },
    })
  }, 1000)
}
const up = async (id) => {
  uni.showLoading({
    title: '上线中',
    mask: true,
  })
  await upCourse(id)
  refreshPrev()
}
const down = async (id) => {
  uni.showLoading({
    title: '下线中',
    mask: true,
  })
  await downCourse(id)
  refreshPrev()
}
const deleteCourseService = async (id) => {
  uni.showLoading({
    title: '上传中',
    mask: true,
  })
  await deleteCourse(id)
  refreshPrev()
}
</script>
<template>
  <view>
    <uv-loading-page
      :loading="loading"
      loading-text="查询中..."
      font-size="30rpx"
    ></uv-loading-page>
    <view
      style="
        padding: 40rpx;
        border-radius: 20rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
      "
    >
      <uv-form labelPosition="top" :model="params" :rules="rules" ref="formRef">
        <uv-form-item label="标题" prop="title" borderBottom>
          <uv-input
            v-model="params.title"
            border="none"
            placeholder="请输入科普视频标题"
            :disabled="props.index !== 0"
          >
          </uv-input>
        </uv-form-item>
        <!-- 分类联动 -->
        <uv-form-item label="分类" prop="category" @click.stop="openPicker()" borderBottom>
          <span style="margin-left: 4px">{{ params.category }}</span>
          <uv-picker
            ref="picker"
            :columns="columns"
            @confirm="confirm"
            @change="change"
          ></uv-picker>
        </uv-form-item>
        <!-- 描述 -->
        <uv-form-item prop="description" borderBottom>
          <uv-textarea
            v-model="params.description"
            count
            placeholder="请输入科普视频描述"
            maxlength="255"
            autoHeight
            :disabled="props.index !== 0"
          ></uv-textarea>
        </uv-form-item>
        <uv-form-item prop="url" borderBottom>
          <!-- 上传视频 -->
          <view style="margin: 0 auto">
            <button
              v-if="props.index === 0"
              @tap="upload"
              style="
                font-size: 28rpx;
                margin-bottom: 20rpx;
                text-align: center;
                background-color: #1a966c;
                border-radius: 20px;
                color: #fff;
              "
            >
              上传科普视频
            </button>
            <video :src="params.url" style="margin-bottom: 15rpx; border-radius: 20rpx"></video>
          </view>
        </uv-form-item>
        <!-- 按钮 -->
        <view style="width: 70%; margin: 0 auto">
          <!-- 待审核 -->
          <view v-if="props.index === 0">
            <uv-button
              type="primary"
              text="保存"
              shape="circle"
              customStyle="margin-top: 10px"
              @click="save"
            ></uv-button>
            <uv-button
              type="success"
              text="提交审核"
              shape="circle"
              customStyle="margin-top: 10px"
              @click="submit"
            ></uv-button>
            <uv-button
              type="warning"
              text="删除"
              shape="circle"
              customStyle="margin-top: 10px"
              @click="deleteCourseService(props.id)"
            ></uv-button>
          </view>
          <!-- 审核通过 -->
          <view v-if="props.index === 1">
            <uv-button
              type="success"
              text="发布课程"
              shape="circle"
              customStyle="margin-top: 10px"
              @click="uploadCourse"
            ></uv-button>
          </view>
        </view>
        <!-- 审核不通过 -->
        <view v-if="props.index === 2">
          <span>审核意见:</span>
          <uv-form-item>
            <uv-textarea disabled autoHeight :value="params.auditMind"></uv-textarea>
          </uv-form-item>
          <uv-form-item>
            <uv-button
              type="primary"
              text="重新编辑"
              shape="circle"
              customStyle="margin-top: 10px"
              @click="reEdit()"
            ></uv-button>
          </uv-form-item>
        </view>
        <!-- 下架或上架按钮 -->
        <view v-if="props.index === 3">
          <uv-button
            type="success"
            text="上线"
            shape="circle"
            customStyle="margin-top: 10px"
            @click="up(props.id)"
          ></uv-button>
          <uv-button
            type="error"
            text="下架"
            shape="circle"
            customStyle="margin-top: 10px"
            @click="down(props.id)"
          ></uv-button>
          <uv-button
            type="warning"
            text="删除"
            shape="circle"
            customStyle="margin-top: 10px"
            @click="deleteCourseService(props.id)"
          ></uv-button>
        </view>
      </uv-form>
    </view>
  </view>
</template>

<style scoped></style>
